#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/5/27 13:29
# @Author : wn 
# @File: dbinfo.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

from django.shortcuts import render, HttpResponse, redirect
from Manager.models import *
from Rbac.models import *
from Manager.views.service import my_page
from django.http import JsonResponse
import json
from Rbac.utils.encrypt import encryptPassword

from Rbac.utils.login_deco import *
import datetime


@auth
def dbinfo_list(request):
    # 当前在第几页
    off = request.GET.get('offset', None)
    # 一页几条数据
    lim = request.GET.get('limit', None)
    # 获取url后拼接的search
    search = request.GET.get('search', None)
    # 判断url后面是否拼接了search，没有，返回页面；有显示搜索条件的值
    if search is None:
        return render(request, 'dbinfo.html')
    else:
        # 按搜索条件获取值
        if search:
            dbinfo_list = Dbinfo.objects.values().filter(dbtype__contains=search)
        else:
            dbinfo_list = Dbinfo.objects.values()
        # 把queryset转成列表[{},{}]
        dbinfo_list = list(dbinfo_list)
        for item in dbinfo_list:
            item['option'] = item['dbtype']
        result = my_page(dbinfo_list, lim, off)
        return JsonResponse(result, safe=False)


# 添加，修改，删除
def dbinfo_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    ismodify = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='dbinfo_list(modify)')
    if request.method == 'GET':
        # dbtype:主键名
        dbinfo_id = request.GET['dbtype']
        item = Dbinfo.objects.values().filter(dbtype=dbinfo_id).first()
        # print('被修改的值：', item)
        if item:
            return JsonResponse(item, safe=False)
    else:
        try:
            if request.POST.get('delete', None):
                # 删除
                dbtype = request.POST.get('id')
                try:
                    Dbinfo.objects.filter(dbtype=dbtype).delete()
                    return HttpResponse('y')
                except Exception as e:
                    # print(e)
                    return HttpResponse('')
            else:
                data = request.POST
                if Dbinfo.objects.filter(dbtype=json.loads(data['dbtype'])[0]).count() >= 1:
                    # 修改
                    if ismodify:
                        if json.loads(data['ismd5'])[0] == False:
                            # 勾选未加密，对密码 加密
                            Dbinfo.objects.filter(dbtype=json.loads(data['dbtype'])[0]).update(
                                dbconnstr=json.loads(data["dbconnstr"])[0],
                                dbusername=json.loads(data['dbusername'])[0],
                                dbpassword=encryptPassword(json.loads(data['dbpassword'])[0]),
                                updatetime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            )
                        else:
                            # 勾选已加密，不对密码做处理
                            Dbinfo.objects.filter(dbtype=json.loads(data['dbtype'])[0]).update(
                                dbconnstr=json.loads(data["dbconnstr"])[0],
                                dbusername=json.loads(data['dbusername'])[0],
                                dbpassword=json.loads(data['dbpassword'])[0],
                                updatetime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            )
                        return HttpResponse('y')
                    else:
                        return HttpResponse("该用户无操作权限！")
        except Exception as e:
            return HttpResponse(e)
    return render(request, 'dbinfo.html')
